package luke4fun.wheresmymoney;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;

import java.util.Calendar;

import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.adapter.list.impl.BudgetDetailListAdapter;
import luke4fun.wheresmymoney.bean.BudgetDetailBean;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.DBConstants;
import luke4fun.wheresmymoney.fragments.DatePickerFragment;
import luke4fun.wheresmymoney.service.async.EditBudgetDetailAsyncTask;
import luke4fun.wheresmymoney.util.DateUtil;
import luke4fun.wheresmymoney.util.FormatUtil;

public class AddBudgetActivity extends FragmentActivity {

	private Context context;
	private EditText budgetFromET;
	private EditText budgetToET;
	private EditText budgetET;
	private ListView detailList;
	private View actionBarView;
	
	private BasicAdapter<BudgetDetailBean> adapter;
	private AccDBHelper dbHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_budget);
		context = this;
		
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setCustomView(R.layout.menu_layout_edit);
		
		initView();
		setView();
		setListener();
	}
	
	@Override
	public void onStart() {
		super.onStart();
		dbHelper = new AccDBHelper(context);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		new EditBudgetDetailAsyncTask(context, adapter).execute();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	private void initView() {
		budgetFromET = (EditText) findViewById(R.id.budget_from);
		budgetToET   = (EditText) findViewById(R.id.budget_to);
		budgetET     = (EditText) findViewById(R.id.budget);
		detailList	 = (ListView) findViewById(R.id.detail_list);
		adapter		 = new BudgetDetailListAdapter(context);
		detailList.setAdapter(adapter);
		actionBarView = getActionBar().getCustomView();
	}
	
	private void setView() {
		final Calendar c 	= Calendar.getInstance();
		int year			= c.get(Calendar.YEAR);
		int month			= c.get(Calendar.MONTH);
		c.clear();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month);
		
		DateUtil.getCurrentMonthInMillis();
		// set up datepicker dialog
		budgetFromET.setText((month + 1) + "/" + 1 + "/" + year);
		budgetToET.setText((month + 2) + "/" + 1 + "/" + year);
	}
	
	private void setListener() {
		final long timeInMillis = DateUtil.getCurrentMonthInMillis();
		budgetFromET.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogFragment dialog = DatePickerFragment.newInstance(v, timeInMillis);
				dialog.show(getSupportFragmentManager(), "datepicker");
			}
		});
		
		budgetToET.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogFragment dialog = DatePickerFragment.newInstance(
											v, DateUtil.getNextMonthInMillis(timeInMillis));
				dialog.show(getSupportFragmentManager(), "datepicker");
			}
		});
		
		budgetET.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				int max = TextUtils.isEmpty(s.toString()) ?
							0 : Integer.parseInt(s.toString());
				
				((BudgetDetailListAdapter) adapter).updateMax(max);				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
		});
		
		actionBarView.findViewById(R.id.action_ok).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
				saveBudget();
				((Activity) context).finish();
			}
		});
		
		actionBarView.findViewById(R.id.action_cancel).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyboard();
				((Activity) context).finish();
			}
		});
	}
	
	private void saveBudget() {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.beginTransaction();

		try {
			// parse date to milliseconds
			long from = FormatUtil.parseDateFromMMddyyyy(budgetFromET.getText().toString()).getTime();
			long to = FormatUtil.parseDateFromMMddyyyy(budgetToET.getText().toString()).getTime();
			int budget = Integer.parseInt(budgetET.getText().toString());
			
			// 1) insert budget
			ContentValues cv = new ContentValues();
			cv.put(DBConstants.BUDGET_FROM, from);
			cv.put(DBConstants.BUDGET_TO, to);
			cv.put(DBConstants.BUDGET_BUDGET, budget);
			long pid = db.insert(DBConstants.TABLE_BUDGET, null, cv);

			// 2) insert detail
			int count = adapter.getCount();
			for (int i=0; i<count; i++) {
				BudgetDetailBean dtl = (BudgetDetailBean) adapter.getItem(i);
				cv.clear();
				cv.put(DBConstants.BUDGET_DETAIL_PID, pid);
				cv.put(DBConstants.BUDGET_DETAIL_CATEGORY, dtl.getCategoryId());
				cv.put(DBConstants.BUDGET_DETAIL_BUDGET, dtl.getBudget());
				db.insert(DBConstants.TABLE_BUDGET_DETAIL, null, cv);
			}
			db.setTransactionSuccessful();
		} catch (NumberFormatException e) {
			Log.e("ZJ", "parsing price error: " + e.getMessage());
		} catch (Exception e) {
			Log.e("ZJ", "saving accounting error: " + e.getMessage());
		}
		db.endTransaction();
		db.close();
	}
	
	public void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(budgetET.getWindowToken(), 0);
	}
}
